package club.janna.rpcdemo.server.codec;

import club.janna.rpcdemo.codec.Codec;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class RPCEncoder extends ChannelOutboundHandlerAdapter {
    private Codec codec;
    public RPCEncoder(Codec codec) { this.codec = codec; }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        log.debug("返回数据 -> {}", msg);
        // 编码成字节
        byte[] bytes = codec.encode(msg);
        log.debug("返回数据长度 -> {}", bytes.length);
        ctx.write(Unpooled.wrappedBuffer(bytes));
    }
}